package com.example.java_chatroom_redis_rabbitmq.component;

import com.example.java_chatroom_redis_rabbitmq.constants.Constant;
import com.example.java_chatroom_redis_rabbitmq.model.Message;
import com.example.java_chatroom_redis_rabbitmq.model.User;
import com.example.java_chatroom_redis_rabbitmq.service.UserService;
import com.example.java_chatroom_redis_rabbitmq.utils.RabbitUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class WebSocketComponent extends TextWebSocketHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RabbitUtil rabbitUtil;
    @Autowired
    private WebSocketSessionManager webSocketSessionManager;
    private long startTime;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        User user = (User) session.getAttributes().get("user");
        Integer userId = user.getUserId();
        if (webSocketSessionManager.getSessionByUserId(userId) == null) {
            webSocketSessionManager.addSession(userId,session);
            startTime = System.currentTimeMillis();
            log.info("websocket连接成功!");
        }else {
            log.info("用户:" + userId + "已存在，登录失败");
            session.close();
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        Message message1 = objectMapper.readValue(message.getPayload(),Message.class);
        String json = objectMapper.writeValueAsString(message1);
        if (message1.getType().equals("message")) {
            rabbitUtil.sendMessage(message1.getFromName() + ".exchange","message", json);
        }else if (message1.getType().equals("friend")) {
            rabbitUtil.sendMessage(message1.getFromName() + ".exchange","message", json);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("websocket连接异常" + exception.toString());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        User user = (User) session.getAttributes().get("user");
        Integer userId = user.getUserId();
        webSocketSessionManager.removeSessionByUserId(userId);
        log.info("websocket断开连接成功!");
        long endTime = System.currentTimeMillis();
        //根据用户七天之内的在线时间为用户设置标签
        long interval = endTime - startTime;
        String key = Constant.redisOnlineTime + userId;
        String ret = redisTemplate.opsForValue().get(key);
        if (ret == null) {
            //设置过期时间为七天
            redisTemplate.opsForValue().set(key,String.valueOf(interval),24*7, TimeUnit.HOURS);
        }else {
            redisTemplate.opsForValue().increment(key,interval);
            long onlineTime = Long.parseLong(redisTemplate.opsForValue().get(key));
            if (onlineTime >= Constant.superStand) {
                userService.updateUserTag(userId,"super");
            }else if (onlineTime >= Constant.activeStand) {
                userService.updateUserTag(userId,"active");
            }
        }
    }
}
